﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Resources;
using System.Xml;
using System.Xml.Linq;
using Com.CodePlex.SPC3.SPbAM.Model;

namespace Com.CodePlex.SPC3.SPbAM.Data {

	public class ServerRepository : Repository {

		public void Load(Server server /*, Action<int> ReportProgress*/) {
			/*
			int iterations = 100;
			for (int i = 0; i < iterations; i++) {
				System.Threading.Thread.Sleep(500 / iterations);
				ReportProgress(i + 1);
			}
			 * */
			if (File.Exists(server.Filename)) {
				XElement root = XDocument.Load(server.Filename).Root;
				server.ActionResults = root
					.Elements("actionresults").Elements("actionresult")
					.Select(i => new ActionResult {
						Action = i.Attribute("action").Value,
						Date = DateTime.Parse(i.Attribute("date").Value),
						Results = i.Elements("results").Elements("result").Select(j => j.Value).ToList()
					}).ToList();
			}

            //todo: load config
		}

		public void Save(Server server /*, string filename, Action<int> ReportProgress*/) {
			/*
			int iterations = 100;
			for (int i = 0; i < iterations; i++) {
				System.Threading.Thread.Sleep(1000 / iterations);
				ReportProgress(i + 1);
			}
			 * */
			//http://stackoverflow.com/questions/4404053/build-xml-using-linq-to-objects
			XElement xml = new XElement("server",
				new XElement("actionresults",
					from i in server.ActionResults
					select new XElement("actionresult",
						new XAttribute("action", i.Action),
						new XAttribute("date", i.Date),
						new XElement("results",
							from j in i.Results
							select new XElement("result", j)
						)
					)
				)
			);
			xml.Save(server.Filename);
		}
	}
}